import { tauri } from "@tauri-apps/api"
import { recv } from "../recv";
import { appWindow } from "@tauri-apps/api/window";
import { UnlistenFn } from "@tauri-apps/api/event";

let unlisten: UnlistenFn|null = null;

function removeListen() {
    if (unlisten != null) {
        unlisten();
        unlisten = null;
    }
}

async function listen() {
    removeListen();
    unlisten = await appWindow.listen<number[]>('SERIAL_RECV_EVENT', (event) => {
        recv(event.payload);
    });
}

listen();

export default {

    async serialPortNames() {
        return await tauri.invoke('serial_port_names') as string[];
    },

    async serialPortIsOpen() {
        return await tauri.invoke('serial_port_is_open') as boolean;
    },

    async serialPortOpen(name: string) {
        
        await tauri.invoke('serial_port_open', {
            'name': name
        });
    },

    async serialPortClose() {
        removeListen();
        await tauri.invoke('serial_port_close');
    },

    async serialPortWrite(buf: number[]) {
        await tauri.invoke('serial_port_write', {
            'buf': buf
        });
    }
}
